package com.skyline.search.index.impl;

import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.lucene.document.Document;
import com.skyline.search.config.Config;
import com.skyline.search.config.ConfigItem;
import com.skyline.search.index.IndexProxy;
import com.skyline.search.index.Indexer;

/**
 * Class <code>IndexProxyImpl</code> IndexProxyImpl是对IndexProxy的实现
 * 
 * @author Jairus Chan
 * @version 0.1, 11/30/10
 * @since JDK1.6
 */

public class IndexProxyImpl extends UnicastRemoteObject implements IndexProxy {
	private static final long serialVersionUID = 1L;
	Map<String, Indexer> indexers = new HashMap<String, Indexer>();

	public IndexProxyImpl(Config config) throws IOException, RemoteException {
		super();
		inital(config);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void inital(Config config) throws IOException, RemoteException {
		@SuppressWarnings("static-access")
		Map<String, ConfigItem> indexPathesMap = config.getConfigProperties();
		Iterator indexPathes = indexPathesMap.entrySet().iterator();
		while (indexPathes.hasNext()) {
			Map.Entry entry = (Map.Entry) indexPathes.next();
			String index = (String) entry.getKey();
			ConfigItem configItem = (ConfigItem) entry.getValue();
			Indexer indexer = new IndexerImpl();
			indexer.inital(configItem.getIndexpath(), configItem.getBathdoc());
			indexers.put(index, indexer);
		}
	}

	public Indexer getIndexer(String index) throws RemoteException {
		return indexers.get(index);
	}

	@Override
	public void createIndex(Document d, String index) throws RemoteException {
		Indexer indexer = getIndexer(index);
		indexer.createIndex(d);
	}

	@Override
	public void addDocument(Document d, String index) throws RemoteException {
		Indexer indexer = getIndexer(index);
		indexer.addDocument(d);
	}

	@Override
	public void deleteDocument(int docID, String index) throws RemoteException {
		Indexer indexer = getIndexer(index);
		indexer.deleteDocument(docID);
	}

	@Override
	public void deleteDocuments(String key, String value, String index)
			throws RemoteException {
		Indexer indexer = getIndexer(index);
		indexer.deleteDocuments(key, value);
	}

	@Override
	public void modifyDocument(Document doc, String index)
			throws java.rmi.RemoteException {
		Indexer indexer = getIndexer(index);
		indexer.modifyDocument(doc);
	}

	@Override
	public void optimize(String index) throws RemoteException {
		Indexer indexer = getIndexer(index);
		indexer.optimize();
	}
}
